from model import Wiki

class PositionManager(object):
    """
    """
    def __update_other_position(self, wiki, up):
        '''
        '''
        # create a query to find a wiki from title
        wikis = Wiki().all()
        # with the same language
        wikis.filter('language =', wiki.language)
        # in the same category
        wikis.filter('category =', wiki.category)
        # with the same position
        wikis.filter('position =', wiki.position)

        # look for the other wiki position to update
        for w in wikis:
            # wiki already updated, we want to update the other
            if not w.key() == wiki.key():
                # up or down
                if up:
                    w.position = wiki.position + 1

                else:
                    w.position = wiki.position - 1

                # save
                w.put()

                # we can leave now
                return

    def __position_update(self, wiki, up):
        '''
        '''
        # retrieve the wiki to be updated
        wikis = Wiki().all()
        wikis.filter('language = ', wiki.language)
        wikis.filter('category =', wiki.category)
        nb_of_wikis = wikis.count()

        # get the current position for update
        position = wiki.position

        #
        updated = False

        #
        if up and position > 1:
            #
            position -= 1

            #
            updated = True

        if not up and position < nb_of_wikis:
            #
            position += 1

            #
            updated = True

        if updated:
            #
            wiki.position = position

            # update the db
            wiki.put()

            # update the other position
            self.__update_other_position(wiki, up)

    def position(self, wiki_key, up):
        '''
        '''
        #
        wiki = Wiki().get(wiki_key)

        if not wiki.position:

            # retrieve the wiki to be updated
            query = Wiki().all()
            query.filter('language =', wiki.language)
            query.filter('category =', wiki.category)

            nb_of_wikis = query.count()

            wiki.position = nb_of_wikis

            # save wiki
            wiki.put()

        #
        self.__position_update(wiki, up)
